package lion.framework.core.conf;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lion.dev.lang.MapJ;
import lion.framework.core.bean.BeanFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <pre>
 * time   2013年8月5日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class ConfigManager {

	public static void addConfig(String name, Config config) {

		configMap.put(name, config);
	}
	public static Config getConfig(String name) {

		Config config = configMap.get(name);
		if (config == null) {
			IConfigLoader loader = null;
			try {
				loader = getLoader(name);
			} catch (Exception e) {
				log.error("", e);
			}

			if (loader != null) {
				config = new Config(loader);
				addConfig(name, config);
				try {
					config.load();
				} catch (Exception e) {
					log.error("load config error", e);
				}
			}

		}
		return config;
	}

	public static void registConfigLoader(String name, Class<? extends IConfigLoader> clazz) {

		loaders.put(name, clazz);
	}

	private static IConfigLoader getLoader(String name) throws Exception {

		Config config = configMap.get("framework");
		if (config == null) { throw new Exception("framework config not initialized"); }

		List<MapJ> configs = config.getList("framework.config");
		MapJ conf = null;
		for (MapJ m : configs) {
			if (name.equals(m.getString("name"))) {
				conf = m;
				break;
			}
		}
		if (conf == null) { return null; }

		Class<? extends IConfigLoader> clazz = loaders.get(conf.getString("loader"));

		IConfigLoader loader = BeanFactory.create(clazz, conf);

		return loader;
	}

	private static Map<String, Config> configMap = new HashMap<>();

	private static Map<String, Class<? extends IConfigLoader>> loaders = new HashMap<>();

	private static Log log = LogFactory.getLog(ConfigManager.class);
}
